﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity.Model;

namespace DAL
{
    public class DepartmentDAO : EnittyDAO
    {
        /// <summary>
        /// load the department via the sys_user permission
        /// </summary>
        /// <param name="sUser"></param>
        /// <returns></returns>
        public List<Department> LoadDepartmentMenuTree(Sys_User sUser)
        {
            try
            {
                List<Department> dpmList=new List<Department>();
                DataContextManager mgr = new DataContextManager();
                if (sUser.IsSuperAdministrator)
                {
                    dpmList = mgr.CurrentDataContext.Department.ToList();
                }
                else
                {
                    string start;
                    var q1 = from dpm in mgr.CurrentDataContext.Department
                             join role in mgr.CurrentDataContext.Sys_DepartmentRole
                             on dpm.ID equals role.DepartmentID
                             //where role.RoleID == sUser.Sys_RoleID
                             select dpm;
                    start = q1.FirstOrDefault().ParentDNA;

                    var query = from d in mgr.CurrentDataContext.Department
                                where d.ParentDNA.StartsWith(start)
                                select d;
                    dpmList = query.ToList();

                }

                return dpmList;
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public Department GetDepartmentByName(Department dx)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                return mgr.CurrentDataContext.Department.Where(d => d.DepartmentName == dx.DepartmentName && d.ParentID == dx.ParentID).FirstOrDefault();
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="d"></param>
        public void AddDepartment(Department d)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                mgr.CurrentDataContext.Department.InsertOnSubmit(d);
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}
